<template>
  <div >
    <n-card title="插件列表" header>
      <div class="header">
        <div>
          <NButton type="primary" @click="onClickAdd">
            添加插件
          </NButton>
        </div>
        <div>
          <n-input-group>
              <n-input v-model:value="params.keyword" clearable placeholder="请输入插件关键词" :style="{ width: '100%' }" />
              <n-button @click="List" type="primary" ghost>
                搜索
              </n-button>
            </n-input-group>
        </div>
      </div>
    </n-card>
    <div class="box" :style="'height:'+innerHeights">
       <!-- 数据表 -->
      <div class="table-box">
        <div >
          <n-data-table
            striped 
            :loading="messageParams.loading"
            ref="table"
            :columns="columns"
            :data="data"
   
          />
        </div>
       
        <!-- 不良状态 -->
        <!-- <div v-for="(item, index) in messageList" v-else :key="index">
          <n-result

            v-if="messageParams.status == item.status"
            :status="item.status"
            :title="item.title"
            :description="item.description"
          >
            <template #footer>
              <NButton>{{ item.button }}</NButton>
            </template>
          </n-result>
        </div> -->
      </div> 
        

    </div>
     <div class="pagination">
            <div>共{{pagination.total}}条数据</div>
            <div>
              <n-pagination
                :page="params.pageNum"
                :page-size="params.pageSize"
                :item-count="pagination.total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
            />
            </div>
        </div>

   <!-- <n-modal  v-model:show="showModal"
      :mask-closable="false"
      preset="dialog"
      :title="popTitle"
      content="你确认?"
      positive-text="确认"
      negative-text="算了"
      @positive-click="submitCallback"
      @negative-click="cancelCallback"
      >
      <div class="box-modal">
         
      </div>
  </n-modal> -->

   <yingModal  :title="popTitle" @close="cancelCallback" @confirm="submitCallback" :SkuShow="showModal" >
      <template #content>
        <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        
        >
          <n-form-item label="插件名" path="title">
            <n-input v-model:value="formValue.title" placeholder="请输入插件名" />
          </n-form-item>
          <n-form-item label="插件图片" path="image">
            <!-- <n-input v-model:value="formValue.image" placeholder="请输入插件图片" /> -->
            <div @click="uploadShow=true" v-if="formValue.image" style="height:135px;width:100px;overflow: hidden;display: flex;padding:12px;
                justify-content: center; align-items: center;">
                <n-image
                :preview-disabled="true"
                style="object-fit: contain;display: flex;
                    justify-content: center;
                    align-items: center;"
                :src="Https()+formValue.image"/>
            </div>
             <div v-else @click="uploadShow=true" class="imageUpload">
              <n-icon size="24" color="rgb(49, 108, 114)">
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><g fill="none"><path d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z" fill="currentColor"></path></g></svg>
              </n-icon>
            </div>
          </n-form-item>
          <n-form-item label="插件描述" path="plugsDescribe">
            <n-input v-model:value="formValue.plugsDescribe" placeholder="请输入插件描述" />
          </n-form-item>
          <n-form-item label="插件类型" path="plugsType">
            <n-input v-model:value="formValue.plugsType" placeholder="请输入插件类型" />
          </n-form-item>
          <n-form-item label="插件路径" path="paths">
            <n-input v-model:value="formValue.paths" placeholder="请输入插件路径" />
          </n-form-item>
          <n-form-item label="状态" path="status">
            <n-switch v-model:value="formValue.status">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
      </template>
  </yingModal>
  
  <!-- <n-modal  v-model:show="uploadShow"
      :mask-closable="false"
      preset="dialog"
      style="width: 1000px;"
      :title="'文件管理'"
      content="你确认?"
      positive-text="确定"
      negative-text="关闭"      
      @positive-click="uploadShow=false"
      @negative-click="uploadShow=false"
      >
      <div class="box-upload">
         <Upload type="1" @selectImage="selectImageFun"/>
      </div>
  </n-modal> -->
   <yingModal  :title="'文件管理'" @close="uploadShow=false" @confirm="uploadShow=false" :SkuShow="uploadShow" >
      <template #content>
        <Upload type="1" @selectImage="selectImageFun"/>
      </template>
  </yingModal>
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue"
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import Upload from "@/views/upload/index.vue"
import api from './api'
import { Https } from "@/utils"
// const router = useRouter()
const uploadShow = ref(false);
const innerHeights = ref(0);
onMounted(() => {
  innerHeights.value = String(window.innerHeight - 280)+'px'
  List()
})


const selectImageFun =(selectImageList) =>{
  formValue.value.image = selectImageList[0];  // 只获取第一张图
  uploadShow.value =false
} 

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const popTitle:any = ref('添加商品分类');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  plugin_id:'all'
})
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const messageList: any = ref([
  {
    status: '500',
    title: '500 服务器错误',
    description: '服务器出错可能说明该雇更多程序员了',
    button: '散财消灾',
  },
  {
    status: '404',
    title: '404 资源不存在',
    description: '生活总归带点荒谬',
    button: '找点乐子吧',
  },
  {
    status: '403',
    title: '403 禁止访问',
    description: '总有些门是对你关闭的',
    button: '放轻松',
  },
])

const formValue = ref({
  title:"",
  image:"",
  plugsDescribe:"",
  plugsType:"",
  status:true,
  paths:""
})

const rules = {

  title: {
    required: true,
    message: '请输入插件名称',
    trigger: 'blur'
  },
  image: {
    required: true,
    message: '请上传插件图标',
    trigger: ['image']
  },

  plugsDescribe: {
    required: true,
    message: '请输入插件描述',
    trigger: ['input']
  },
  plugsType: {
    required: true,
    message: '请输入插件类型',
    trigger: ['input']
  },
  paths: {
    required: true,
    message: '请输入插件路径',
    trigger: ['input']
  },
  
}

const columns = [
  {
    title: '插件ID',
    key: 'plugin_id',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: '插件名称',
    key: 'title',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '插件类型',
    key: 'plugsType',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '描述',
    key: 'plugsDescribe',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '图片',
    render: ({ image }) => {
      // console.log(image)
      return h(NImage, {
        width: 60,
        src: Https()+image,
      })
    },

  },
  {
    title: '插件路径',
    key: 'paths',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:database' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.plugin_id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

function setStatus(item){
    // console.log(item)
    if(item.status)
        return h('span', { style: { color: 'green' } },'启用')
    else
        return h('span', { style: { color: 'red' } },'禁用')
}
const data: any = ref([])

async function handleDelete(id){
  const res: any = await api.DeleteApi({
    plugin_id:id
  })

  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}

const handleOpenRolesSet =(item) =>{
    
    formValue.value = item;
    popTitle.value = '编辑';
    showModal.value = true;
} 

async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加商品分类'
  showModal.value = true
  formValue.value = {
    title:"",
    image:"",
    plugsDescribe:"",
    plugsType:"",
    status:true,
    paths:""
  }
}
async function submitCallback() {
  messageParams.value.loading = true
  formRef.value?.validate((errors) => {
    if (!errors) {
      if(popTitle.value == '添加商品分类')
        AddFun();
      else
        EditFun();
    }
    else {
      showModal.value = true
      return 
 
    }
  })
}

async function AddFun(){
  const res: any = await api.AddApi(formValue.value)
  if(res.code == 200){
    List();
    showModal.value = false;
    $message.success('添加成功!')
  }else{
    $message.error(res.message)
  }
}

async function EditFun(){
  const res: any = await api.EditApi(formValue.value)
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
  params.value.pageNum = 1
  params.value.pageSize = size
  List();
}


function cancelCallback() {
  
  List();
  showModal.value = false
}
</script>

<style scoped>
 .box {
    /* height: 75vh; */
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 400px;
}
.pagination{
  display: flex;
  justify-content: right;
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right: 30px;
}
.header{
  display: flex;
  gap: 10px;
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
